import { api } from "./api";

export const adm = {
  getData(params, body, sid) {
    body.sid = sid;
    const { type, tab } = params;
    const allowTabs = ["banner", "banner-adm", "mp-config"];
    if (!allowTabs.includes(tab)) {
      throw "Invalid tab:" + tab;
    }
    return api.getData(type, tab, body);
  },
  async getShopList(body) {
    body._data = 1;
    return api.getShops(body, "/data/list/shop-adm");
  },
  async getShopInfo(body) {
    const row = await api.getShopRow(body);
    if (!row) throw "门店不存在";
    return row;
  },
  async postShopEdit(body, user) {
    const sysAdm = user.role == 1;
    if (body.id) {
      const row = await api.getShopRow(body.id);
      if (!row) {
        throw "门店不存在";
      }
      if (!sysAdm && row.id != user.sid) {
        throw "无此门店权限";
      }
    } else {
      if (!sysAdm) throw "无系统权限";
    }
    return api.postShop(body);
  },

  async getGoodsList(body, sid) {
    body._data = 1;
    body.sid = sid;
    return api.getGoodsList(body, "/data/list/goods-adm");
  },
  async postGoodsEdit(body, sid) {
    if (!sid) {
      throw "无权限";
    }
    if (body.id) {
      const row = await api.getGoodsRow(body.id);
      if (!row || row.sid != sid) {
        throw "商品已删除 或 无权限";
      }
    } else {
      body.sid = sid;
    }
    return api.postGoods(body);
  },

  async getOrders(body, user) {
    if (!user.role) {
      throw "无权限";
    }
    body._data = 1;
    if (user.sid) {
      body.sid = user.sid;
    }
    return api.getOrderList(body, "/data/list/order-adm");
  },

  async getNfcList(body, user) {
    if (!user.sid) {
      throw "无权限";
    }
    body.sid = user.sid;
    body._data = 1;
    let data = await api.getNfcRows(body);
    if (body.nfc_id && body._page == 1) {
      const isIn = data.rows.find((it) => it.nfc_id == body.nfc_id);
      if (!isIn) {
        await this.postNfc(
          {
            nfc_id: body.nfc_id,
          },
          user
        );
        data = await api.getNfcRows(body);
      }
    }
    return data;
  },
  async postNfc(body, user) {
    if (!user.sid) {
      throw "无权限";
    }
    if (!body.id) {
      body.sid = user.sid;
      const [maxSeqRow] = await api.getNfcRows({
        sid: body.sid,
        _order: "seq desc",
        _limit: 1,
      });
      body.seq = (maxSeqRow?.seq || 0) + 1;
    }
    const data = await api.postNfc(body);
    return data;
  },
  async setOrderFee(body) {
    const { id, fee } = body;
    if (!id) {
      throw "缺少参数";
    }
    if (!(fee >= 0 && fee < 300)) {
      throw "超时费用超出范围";
    }
    const data = await api.postOrderLog({
      id,
      fee,
      pay_info: null,
    });
    return data;
  },
};
